<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="table-view">
      <template #high_form="{ form }">
        <XForm ref="form" :fieldList="highFieldList" :options="formOption" labelPosition="top" :formData="form" :originOption="originOption" class="grid grid-cols-3"> </XForm>
      </template>

      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption"></XForm>
      </template>

      <template #toolbar_btns>
        <el-tabs v-model="activeName" class="tabs" @tab-click="tabHandleClick">
          <el-tab-pane v-for="item in tabOpt" :key="item.key" :name="item.key">
            <template #label>
              {{ item.label }} <span class="text-[#999]">({{ item.total || 0 }})</span>
            </template>
          </el-tab-pane>
        </el-tabs>
        <VButton type="primary" icon="Plus" @click="openConfirmInput('add')">新增</VButton>
        <VButton type="primary" @click="openConfirmInput('audit')">审核</VButton>
        <VButton type="danger" @click="onDiscard">作废</VButton>

        <VButton type="primary" icon="Upload" class="ml-auto" @click="openConfirmInput('add')">导 出</VButton>
        <el-button icon="Download" @click="onImport">导入</el-button>
      </template>
    </VTable>

    <!-- 日志 -->
    <XLog ref="logRef" :api="purchaseMaterialPlanLog"></XLog>
    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="getCurrentConfirm" @submit="handleConfirmSubmit" @close="closeConfirmInput">
      <!-- 编辑 备料单信息 -->
      <template #OrderDtl="{ form }">
        <div class="w-[100%] grid grid-cols-2">
          <VText title="备料计划单" :value="form.plan_no" :line="1" />
          <span class="ml-[40px]"><VText title="状态" :value="form.status" :line="1" /></span>
        </div>
      </template>

      <!-- 编辑 选择SKU -->
      <template #SkuSlot="{ form }">
        <VButton type="primary" @click="DialogAddGoodsRef.open()">{{ form.sku ? "修改" : "添加" }}</VButton>
      </template>
      <!-- 编辑 备料单 商品信息 -->
      <template #GoodsDtl="{ form }">
        <div class="goods-dtl-view">
          <VText title="SKU" :value="form.sku" :line="1" />
          <VText title="商品名称" :value="form.sku_title" :line="1" />
          <VText title="ASIN" :value="form.asin" :line="1" />
          <VText title="运营人员" :value="form.operator_user_text" :line="1" />
          <VText title="供应商" :value="form.supplier_name" :line="1" />
        </div>
      </template>
    </ConfirmInput>
    <!-- 弹窗 表格数据展示 -->
    <DialogTableInfo v-model="dialogTableInfoVisible" v-bind="tableInfoConfirm" />

    <!-- 添加商品弹窗 -->
    <DialogAddGoods ref="DialogAddGoodsRef" @submit="submitAddGoodsRef" />

    <!-- 导入 -->
    <DialogImport v-model:modelValue="visibleImport" :download-url="downloadUrl" :call-back="importCallBack" :api="purchaseMaterialPlanImport" />
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus"
import {
  purchaseMaterialPlanList,
  purchaseMaterialPlanCreate,
  purchaseMaterialPlanEdit,
  purchaseMaterialPlanVerify,
  purchaseMaterialPlanDiscard,
  purchaseMaterialPlanLog,
  purchaseMaterialPlanImport,
} from "@/api/plan"

import DialogImport from "@/components/DialogImport/index.vue"

const visibleImport = ref(false)
const downloadUrl = ref("")

const importCallBack = () => {
  console.log(1887766555)
}
const onImport = async () => {
  // purchaseMaterialPlanImport
  visibleImport.value = true
  console.log(visibleImport.value)

  downloadUrl.value = "https://xc2k-pmc.oss-cn-shenzhen.aliyuncs.com/import_template/%E5%A4%87%E6%96%99%E8%AE%A1%E5%88%92%E7%AE%A1%E7%90%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
  // importUrl.value = "v1/base/stocking-config/import"
  // batchVisible.import = true
}

// 添加商品弹窗
import DialogAddGoods from "./components/DialogAddGoods.vue"
const DialogAddGoodsRef = ref()
// 添加商品 保存
const submitAddGoodsRef = (value = null) => {
  let keys = ["sku", "sku_title", "asin", "operator_user_text", "custom_sku"]
  keys.forEach((key) => {
    getCurrentConfirm.value.form[key] = value[key]
  })
  getCurrentConfirm.value.form.supplier_name = value?.plan_asin_purchases?.supplier_name
}

import XForm from "@/components/XForm/index.vue"
// 日志
import XLog from "@/components/XLog"
const logRef = ref()
// 编辑 备料单 商品信息
import ConfirmInput from "@/components/ConfirmInput/index.vue"
// 弹窗 表格数据展示
import DialogTableInfo from "@/components/DialogTableInfo/index.vue"

import {
  fieldList, // 搜索条件 配置
  highFieldList, // 高级搜索 配置1
} from "./config.jsx"

// 状态
const activeName = ref("")
const tabOpt = ref([
  { label: "全部", key: "", total: 0 },
  { label: "待计划审核", key: "1", total: 0 },
  { label: "待运营审核", key: "2", total: 0 },
  { label: "已审核", key: "3", total: 0 },
  { label: "已驳回", key: "4", total: 0 },
])
const tabHandleClick = (tab, event) => {
  console.log(tab, event)
  tableRef?.value.resetAndQuery()
}

onMounted(() => {
  getOption()
})

import { getEnum } from "@/utils/enumUtils"
import { getSupplie, getCountry } from "@/api"
// 枚举 数据
const originOption = ref({})
// 获取下拉数据
const getOption = async () => {
  const keys = ["plan_type", "goods_active", "sku_status", "sku_resource_status"]
  const data = await getEnum(keys, "enumOptions")
  keys.forEach((key) => {
    originOption.value[key] = data[key]
  })
  originOption.value.supplier = (await getSupplie())?.data
  originOption.value.country = (await getCountry()).data
}

// 作废
const onDiscard = () => {
  let id = getSelectRow()
  console.log(id)
  if (!id.length) return
  purchaseMaterialPlanDiscard({ id }).then((res) => {
    ElMessage.success(res.message)
    query()
  })
}

const tableRef = ref()

const data = reactive({
  batchVisible: false, //  表单编辑 弹窗状态
  getCurrentConfirm: {}, // 表单编辑 配置
})
const { batchVisible, getCurrentConfirm } = toRefs(data)
// 保存 弹窗 表单编辑
const handleConfirmSubmit = (param) => {
  console.log(10087)
  console.log(param)
  console.log(getCurrentConfirm.value)
  let api = null
  //  purchaseMaterialPlanCreate, purchaseMaterialPlanEdit ,purchaseMaterialPlanVerify
  switch (getCurrentConfirm.value.type) {
    case "add": // 新增
      api = purchaseMaterialPlanCreate
      break
    case "edit": // 编辑
      api = purchaseMaterialPlanEdit
      break
    case "audit": // 审核
      api = purchaseMaterialPlanVerify
      break
  }
  api(param)
    .then((res) => {
      console.log(res)
      ElMessage.success(res.message)
      query()
    })
    .finally(() => {
      getCurrentConfirm.value = {}
      batchVisible.value = false
    })
}
// 关闭 弹窗 表单编辑
const closeConfirmInput = () => {
  console.log("closeConfirmInput")
  getCurrentConfirm.value = {
    form: {},
  }
  console.log(getCurrentConfirm.value)
}
const openConfirmInput = (type, params = {}) => {
  console.log("openConfirmInput-------------" + type)
  console.log(params)
  // 新增
  if (type == "add") {
    let confirm = currentConfirmOpt.edit
    confirm.form = { department_name: "", country_name: "" }
    confirm.originOption = originOption.value
    getCurrentConfirm.value = confirm
  }
  // 编辑
  if (type == "edit") {
    let confirm = currentConfirmOpt.edit
    confirm.originOption = originOption.value
    // edit.form = { id: "asasasas" }
    confirm.form = params
    getCurrentConfirm.value = confirm
  }
  // 审核
  console.log(type)
  if (type == "audit") {
    let id = []
    if (params.id) {
      id = [params.id]
    } else {
      let ids = getSelectRow()
      if (!ids.length) return
      id = ids
    }
    let confirm = currentConfirmOpt.audit
    confirm.form = { id }
    confirm.originOption = originOption.value
    getCurrentConfirm.value = confirm
  }
  getCurrentConfirm.value.type = type
  console.log(getCurrentConfirm.value)
  batchVisible.value = true
}

const currentConfirmOpt = {
  edit: {
    title: "新增",
    width: 800,
    formOptions: { inline: true, labelPosition: "top", requireAsteriskPosition: "right" },
    form: {},
    fieldOptions: [
      {
        slot: "OrderDtl",
        show: ({ model }) => !!model?.id,
        style: { width: "100%" },
      },

      {
        field: "type",
        label: "备料类型",
        type: "select",
        options: {
          placeholder: "备料类型",
          data: [
            { label: "FBA备料", value: 1 },
            { label: "海外仓备料", value: 2 },
            { label: "项目产品备料", value: 3 },
          ],
        },
        style: { width: "120px" },
      },

      {
        field: "department_id",
        label: "备料部门",
        type: "cascader",
        cascaderType: "department",
        placeholder: "备料部门",
        itemProps: {
          props: {
            emitPath: false,
            label: "name",
            value: "id",
            children: "sub",
          },
        },
        change: (nodes) => {
          let department_name = nodes?.[0]?.pathLabels?.join("/")
          getCurrentConfirm.value.form.department_name = department_name
        },
        style: { width: "200px" },
      },
      {
        label: "国家",
        field: "country_id",
        type: "select",
        originField: "country",
        options: {
          placeholder: "国家",
        },
        change: (e) => {
          let country_name = originOption.value.country.find((v) => v.value == e)?.label
          getCurrentConfirm.value.form.country_name = country_name
        },
        style: { width: "200px" },
      },
      {
        field: "sku",
        label: "SKU1",
        style: { width: "320px" },
        slot: "SkuSlot",
      },
      { type: "br" },

      // {
      //   field: "custom_sku",
      //   label: "自定义SKU	",
      //   style: { width: "300px" },
      // },
      {
        slot: "GoodsDtl",
        show: ({ model }) => !!model?.sku,
        style: { width: "100%" },
      },
      {
        field: "plan_num",
        label: "备料数量",
        style: { width: "120px" },
      },

      {
        label: "预计交期",
        field: "expect_delivery_time",
        type: "dateTimeRangeNorm",
        itemProps: {
          type: "date",
          shortcuts: [],
          format: "YYYY-MM-DD",
          valueFormat: "YYYY-MM-DD",
        },
        style: { width: "180px" },
      },
      {
        field: "sale_verify_user_id",
        label: "运营审核人员",
        type: "cascader",
        placeholder: "运营审核人员",
        style: { width: "200px" },
      },
      {
        field: "remark",
        label: "备注信息",
        type: "textarea",
        style: { width: "320px" },
        autosize: { minRows: 4, maxRows: 6 },
      },
    ],
    rules: {
      type: [{ required: true, message: "请选择备料类型", trigger: "change" }],
      department_id: [{ required: true, message: "请选择备料部门", trigger: "change" }],
      country_id: [{ required: true, message: "请选择国家", trigger: "change" }],
      sku: [{ required: true, message: "请输入SKU", trigger: "change" }],
      plan_num: [{ required: true, message: "请输入备料数量", trigger: "change" }],
      expect_delivery_time: [{ required: true, message: "请选择预计交期", trigger: "change" }],
      sale_verify_user_id: [{ required: true, message: "请选择运营审核人员", trigger: "change" }],
    },
  },
  audit: {
    title: "审核",
    form: { id: [], status: "" },
    fieldOptions: [
      {
        field: "status",
        label: "状态",
        type: "select",
        options: {
          placeholder: "状态",
          data: [
            { label: "审核通过", value: 1 },
            { label: "已驳回", value: 2 },
          ],
        },
        style: { width: "300px" },
      },
    ],
    formOptions: {
      inline: true,
      labelPosition: "right",
      labelWidth: "130px",
    },
  },
}

// //获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  return getCheckboxRecords.map((v) => v.id)
}

// 查询
const query = () => {
  tableRef?.value.query()
}

const formOption = ref({
  inline: true,
})

// const rowStyle = ({ row, column }) => {
//   return { height: `${row.aaaaa.length * 80}px` }
// }
// 弹窗 表格数据展示
const dialogTableInfoVisible = ref(false)
const tableInfoConfirm = ref({})
const openTableInfo = (e) => {
  console.log(e)
  switch (e) {
    case "1":
      tableInfoConfirm.value = dialogTabelInfoConfig.aaaaa
      break
    case "2":
      tableInfoConfirm.value = dialogTabelInfoConfig.bbbbb
      break
    default:
      break
  }
  dialogTableInfoVisible.value = true
}
const dialogTabelInfoConfig = {
  //
  aaaaa: {
    title: "已下单明细",
    info: { xxxx: "1009988", day: "11" },
    infoColumn: [
      { label: "sku", value: "xxxx" },
      { label: "自定义SKU", value: "day" },
    ],
    tableOptions: {
      border: false,
      columns: [
        { field: "text", title: "采购单号" },
        { field: "address", title: "采购人员" },
        { field: "address", title: "采购时间" },
        { field: "address", title: "状态" },
        { field: "address", title: "收货仓库" },
        { field: "address", title: "采购数量" },
        { field: "address", title: "采购单价/RMB" },
        { field: "address", title: "采购总价/RMB" },
      ],
      pagerConfig: {},
      proxyConfig: {
        // autoLoad: false, // 是否自动加载查询数据
        props: {
          result: "data",
          total: "total",
        },
        ajax: {
          query: ({ page, form }) => {
            const { currentPage: pageNum, pageSize } = page
            return queryListaaaaa()
          },
        },
      },
    },
  },
  bbbbb: {
    title: "剩余库存明细",
    info: { xxxx: "1009988", day: "11" },
    infoColumn: [
      { label: "sku", value: "xxxx" },
      { label: "自定义SKU", value: "day" },
    ],
    tableOptions: {
      border: false,
      columns: [
        { field: "text", title: "类型" },
        { field: "address", title: "单据" },
        { field: "address", title: "添加时间" },
        { field: "address", title: "预计交期" },
        { field: "address", title: "操作" },
        { field: "address", title: "变更数量" },
        { field: "address", title: "可用数量" },
        { field: "address", title: "锁定数量" },
        { field: "address", title: "更新时间" },
      ],
      // data: [{ address: "34234234324234324234523dfghfdhdfshsdgsdsdfgsdg" }],
      pagerConfig: {},
      proxyConfig: {
        // autoLoad: false, // 是否自动加载查询数据
        props: {
          result: "data",
          total: "total",
        },
        ajax: {
          query: ({ page, form }) => {
            const { currentPage: pageNum, pageSize } = page
            return queryListaaaaa()
          },
        },
      },
    },
  },
}

const queryListaaaaa = () => {
  console.log(112233)
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        data: [{ address: "34234234324234324234523dfghfdhdfshsdgsdsdfgsdg" }],
        total: 20,
      })
    }, 1000)
  })
}

const aaaaa = (row) => {
  console.log(row)
}
const statusTagColor = {
  已驳回: "bg-[#FCE5E7] text-[#E50113]",
  已审核: "bg-[#F0F0F2] text-[#333]",
  已驳回: "bg-[#FCE5E7] text-[#E50113]",
}
// 活跃度 状态颜色
const activeColor = {}

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      plan_no: "",
      skuRange: { type: "sku", value: "" },
      timeRange: { type: "created_at", value: "" },
      verifyRange: { type: "plan_verify_user_id", value: "" },
      userRange: { type: "create_by", value: "" },
    },
  },
  rowConfig: { height: "160" },
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },
    {
      title: "备货计划信息",
      width: 220,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <div class={`status-tag dark mr-[2px] ${statusTagColor[row.status_text] || "bg-[#EAF3FF] text-[#3487FF]"}`}>{row.status_text}</div>
              <div class="text-blue">
                <VText value={row.plan_no} />
              </div>
            </div>
            <VText title="备货类型" value={row.type} line={1} />
            <VText title="备料部门" value={row.department_name} line={1} />
            <VText title="预计交期" value={row.expect_delivery_time} line={1} />
          </div>
        ),
      },
    },
    {
      title: "图片",
      width: 120,
      slots: {
        default: ({ row }) => <el-image style="width:80px;height:80px" src={row.goods_pic} />,
      },
    },

    {
      title: "商品信息",
      width: 200,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="SKU" value={row.sku} line={1} type="link" />
            <VText title="自定义" value={row.custom_sku} line={1} />
            <VText title="ASIN" value={row.asin} line={1} />
            <div class="grid grid-cols-2">
              <VText title="国家" value={row.country_name} line={1} />
              <VText title="活跃度" value={row.active_text} line={1} class={activeColor[row.active_text] || "text-green"} />
            </div>
          </div>
        ),
      },
    },
    {
      title: "商品名称",
      width: 120,
      field: "product_name",
      line: 3,
    },
    {
      title: "采购信息",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <VText title="采购价" value={row.purchase_price} line={1} />
              <el-divider direction="vertical" />
              {row.batch_num || "-"}起批
            </div>
            <VText title="采购天数" value={row.purchase_days} line={1} />
            <VText title="单箱数量" value={row.fcl_num} line={1} />
            <VText title="供应商" value={row.supplier} line={1} />
          </div>
        ),
      },
    },
    {
      title: "备料数量",
      width: 120,
      field: "plan_num",
    },
    {
      title: "总金额/RMB",
      width: 120,
      field: "total_price",
    },
    {
      title: "已下单数量",
      width: 120,
      slots: {
        default: ({ row }) => <VText value={row.order_num || "22"} line={1} type="link" onClick={() => openTableInfo("1", row)} />,
      },
    },
    {
      title: "剩余库存",
      width: 120,
      slots: {
        default: ({ row }) => <VText value={row.remaining_stock || "11"} line={1} type="link" onClick={() => openTableInfo("2", row)} />,
      },
    },
    {
      title: "备注信息",
      width: 120,
      field: "remark",
      line: 3,
    },
    {
      title: "人员信息",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="采购" value={row.purchase_user_name} line={1} />
            <VText title="运营" value={row.sale_user_name} line={1} />
            <VText title="添加" value={row.create_user} line={1} />
            <VText title="计划审核" value={row.plan_verify_user_name} line={1} />
            <VText title="运营审核" value={row.sale_verify_user_name} line={1} /> 
          </div>
        ),
      },
    },
    {
      title: "时间信息",
      width: 240,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="添加" value={row.created_at} line={1} />
            <VText title="计划审核" value={row.plan_verify_at} line={1} />
            <VText title="采购审核" value={row.sale_verify_at} line={1} />
          </div>
        ),
      },
    },
    {
      title: "操作",
      width: 60,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => openConfirmInput("edit", row)}>
                编辑
              </el-button>
              <br />
              <el-button link type="primary" onClick={() => openConfirmInput("audit", row)}>
                审核
              </el-button>
              <br />
              <el-button link type="primary" onClick={() => logRef?.value.open({ plan_id: row.id })}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          ...form,
          status: activeName.value,
          page: page.pageNum,
          page_num: page.pageSize,
        }
        console.log(params)
        return queryList(params)
      },
    },
  },
})
const queryList = (params) => {
  return new Promise((resolve, reject) => {
    purchaseMaterialPlanList(params).then((res) => {
      resolve(res)
    })
  })
}
</script>
<style lang="scss" scoped>
.table-view {
  :deep(.vxe-cell) {
    max-height: 100% !important;
  }
  :deep(.fixed-left--wrapper) {
    margin-top: -1px !important;
  }
  :deep(.fixed-right--wrapper) {
    margin-top: -1px !important;
  }
  :deep(.col--fixed) {
    background: #fff;
    z-index: 999;
  }

  :deep(.status-tag) {
    height: 14px;
    line-height: 14px;
    padding: 0 3px;
    text-align: center;
    border-radius: 2px;
    font-size: 10px;
  }
}

:deep(.tabs) {
  margin-top: 0 !important;
  width: 100%;
  .el-tabs__header {
    margin-bottom: 0;
    height: 28px;
    line-height: 28px;
    .el-tabs__nav {
      border-radius: 4px !important;
      overflow: hidden;
    }
  }
  .el-tabs__item {
    height: 28px;
    line-height: 28px;
  }
}
.goods-dtl-view {
  padding: 8px;
  width: 100%;
  background: #eaf3ff;
  border-radius: 4px;
}
</style>
